package c_utils;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    // 2.定义静态变量
    static String driver;
    static String url;
    static String user;
    static String password;
    // 1.在程序启动后就需要进行加载 - 静态代码块
    static {
        //①加载配置文件 - 获取配置文件类
        Properties pro = new Properties();
        //②加载
        try {
            pro.load(JDBCUtils.class.getResourceAsStream("c.properties"));
            //③通过键得到value值
            driver = pro.getProperty("driver");
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
    public static Connection getConnection(){
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url,user,password);
            return conn;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void close(Connection conn, Statement state) {
        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public static void close(Connection conn, Statement state, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        close(conn,state);
    }


}
